﻿using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using ZHDJ.Data.BLL;
using ZHDJ.Data.Models.Common;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;

namespace ZHDJ.Web.Portal.Score
{
    public partial class PartyScoreDetail : PortalPage
    {
        /// <summary>
        /// 页数
        /// </summary>
        private string PageIndex
        {
            get
            {
                return Request["PageIndex"] ?? "";
            }
        }

        /// <summary>
        /// 每页条数
        /// </summary>
        private string PageSize
        {
            get
            {
                return Request["PageSize"] ?? "";
            }
        }

        /// <summary>
        /// 类型
        /// </summary>
        public string Category
        {
            get
            {
                return Request["Category"] ?? "";
            }
        }

        /// <summary>
        /// 类型
        /// </summary>
        public string DDLCategoryValue
        {
            get
            {
                return Request["DDLCategoryValue"] ?? this.hdddlCategoryValue.Value;
            }
        }

        /// <summary>
        /// LoginID
        /// </summary>
        public string LoginID
        {
            get
            {
                return Request["LoginID"] ?? this.CurrentUser.LoginID;
            }
        }

        /// <summary>
        /// BranchID
        /// </summary>
        public string BranchID
        {
            get
            {
                return Request["BranchID"] ?? PartyOrgMember.QueryMemberBranchID(this.CurrentUser.LoginID);
            }
        }

        /// <summary>
        /// ScoreSource
        /// </summary>
        public DataTable ScoreSource
        {
            get
            {
                string objectID = "";
                if (this.Category == "Member")
                    objectID = this.LoginID;
                else
                    objectID = this.BranchID;

                DataTable dt = PartyScoreHelper.GetScoreDetail(objectID, this.DDLCategoryValue, Category, Convert.ToInt32(this.PageIndex), Convert.ToInt32(this.PageSize));
                return dt;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckLogin(true);

            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }

            if (!string.IsNullOrEmpty(this.PageIndex))
            {
                this.WriteList();
            }
            else
            {
                string objectID = "";
                if (this.Category == "Member")
                    objectID = this.LoginID;
                else
                    objectID = this.BranchID;

                this.hfTotalCount.Value = PartyScoreHelper.GetScoreDetail(objectID, this.ddlCategory.SelectedValue, Category);
            }
            hdCategory.Value = this.Category;
            hdLoginID.Value = this.LoginID;
            hdBranchID.Value = this.BranchID;
            hdddlCategoryValue.Value = this.DDLCategoryValue;
        }

        private void BindData()
        {
            IQueryable<PartyObjectScoreRule> q = DB.PartyObjectScoreRules.Where(t => t.ObjectType == this.Category);
            ddlCategory.DataValueField = "Category";
            ddlCategory.DataTextField = "Name";
            ddlCategory.DataSource = q.ToList();
            ddlCategory.DataBind();
            ddlCategory.Items.Insert(0,new System.Web.UI.WebControls.ListItem() { Text = "==请选择==", Value = "" });
        }

        /// <summary>
        /// LoadData
        /// </summary>
        private void LoadData()
        {
            if (Category == "Member")
            {
                this.lbScoreTile.Text = "姓名：";
                this.lbName.Text = ControlBusiness.GetMembersPickerText(this.LoginID);
                DataTable dt = PartyScoreHelper.QueryMemberScore(this.LoginID);
                if (dt != null && dt.Rows.Count > 0)
                {
                    this.lbOrder.Text = Convert.ToDecimal(dt.Rows[0]["Score"]).ToString("#0.00") + "分";
                    this.lbSumScore.Text = Convert.ToDecimal(PartyScoreHelper.GetScoreSum(this.LoginID)).ToString("#0.00") + "分";
                }
            }
            else
            {
                this.lbScoreTile.Text = "组织名称：";
                this.lbName.Text = ControlBusiness.GetBranchPickerText(this.BranchID);
                DataTable dt = PartyScoreHelper.QueryBranchScore(this.BranchID);
                if (dt != null && dt.Rows.Count > 0)
                {
                    this.lbOrder.Text = Convert.ToDecimal(dt.Rows[0]["Score"]).ToString("#0.00") + "分";
                    this.lbSumScore.Text = Convert.ToDecimal(PartyScoreHelper.GetScoreSum(this.BranchID)).ToString("#0.00") + "分";
                }
            }
        }

        private void WriteList()
        {
            StringBuilder sbHtml = new StringBuilder();
            DataTable dt = this.ScoreSource;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sbHtml.AppendFormat("<tr class=\"tr_b\" style=\"height: 30px;\">");
                sbHtml.AppendFormat("<td class=\"td_b\">{0}</td>", dt.Rows[i]["Name"]);
                sbHtml.AppendFormat("<td align=\"right\" class=\"td_b\"><span style=\"color: Red\">{0}</span></td>", dt.Rows[i]["Score"]);
                sbHtml.AppendFormat("<td align=\"center\" class=\"td_b\">{0}</td>", Convert.ToDateTime(dt.Rows[i]["ScoreDate"]).ToString("yyyy-MM-dd HH:mm:ss"));
                sbHtml.AppendFormat("<td class=\"td_b\">{0}</td>", dt.Rows[i]["Description"]);
                sbHtml.Append("</tr>");
            }
            Response.Clear();
            Response.Write(sbHtml.ToString());
            Response.End();
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            string fileName = "";
            if (Category == "Member")
            {
                fileName = string.Format(ControlBusiness.GetMembersPickerText(this.LoginID) + "_个人积分详细记录({0})", DateTime.Now.ToString("yyyy-MM-dd"));
            }
            else
            {
                fileName = string.Format(ControlBusiness.GetBranchPickerText(this.BranchID) + "_组织积分详细记录({0})", DateTime.Now.ToString("yyyy-MM-dd"));
            }

            DataTable dt = this.GetExportData();
            MemoryStream memoryStream = NPOIBusiness.Export(fileName, dt);

            string filePath = Server.MapPath("~/upload/" + fileName + ".xls");
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
            BinaryWriter w = new BinaryWriter(fs);
            w.Write(memoryStream.ToArray());
            fs.Close();
            memoryStream.Close();

            FileInfo info = new FileInfo(filePath);
            long fileSize = info.Length;
            Response.Clear();

            //指定Http Mime格式为压缩包
            Response.ContentType = "application/x-excel";
            //Response.ContentType = "application/x-zip-compressed";

            // Http 协议中有专门的指令来告知浏览器, 本次响应的是一个需要下载的文件. 格式如下:
            // Content-Disposition: attachment;filename=filename.txt
            Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(info.Name));
            //不指明Content-Length用Flush的话不会显示下载进度
            Response.AddHeader("Content-Length", fileSize.ToString());
            Response.TransmitFile(filePath, 0, fileSize);
            Response.Flush();

            info.Delete();
        }

        public DataTable GetExportData()
        {
            string objectID = "";
            if (this.Category == "Member")
                objectID = this.LoginID;
            else
                objectID = this.BranchID;
            DataTable dt = PartyScoreHelper.GetScoreDetail(objectID, DDLCategoryValue, Category, 0, 100000000);

            dt.Columns[0].ColumnName = "积分类型";
            dt.Columns[1].ColumnName = "分数";
            dt.Columns[2].ColumnName = "积分获得时间";
            dt.Columns[3].ColumnName = "积分来源";
            return dt;
        }

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.hdddlCategoryValue.Value = this.ddlCategory.SelectedValue;
        }
    }
}